package com.freak.wanandroid.base.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.freak.httpmanager.BaseViewModel;
import com.freak.httpmanager.utils.TUtil;

import org.jetbrains.annotations.NotNull;


/**
 * MVVM activity基类
 *
 * @author freak
 * @date 2022/09/12.
 */
public abstract class BaseLifecycleActivity<T extends BaseViewModel> extends BaseActivity {
    protected T mViewModel;
    protected AppCompatActivity mActivity;

    /**
     * 在onCreate方法中加载数据
     * 不需要刷新数据则请求数据在此方法中调用
     */
    protected abstract void onCreateLoadData();

    /**
     * 在onResume中加载数据
     * 需要返回刷新数据则选择放在这个方法中加载，否则在onCreateLoadData中加载数据
     */
    protected abstract void onResumeLoadData();

    /**
     * 数据绑定
     */
    protected abstract void dataObserver();


    @SuppressLint("RestrictedApi")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mViewModel = viewModelProviders(this, (Class<T>) TUtil.getInstance(this, 0));
//        App.resetDensity(this, App.DESIGN_WIDTH);
        setContentView(getLayout());
        super.onCreate(savedInstanceState);
        mActivity = this;
        initView();
        initEventAndData();
        onCreateLoadData();
        dataObserver();
    }

    protected <T extends ViewModel> T viewModelProviders(@NotNull AppCompatActivity fragment, @NotNull Class modelClass) {
        return (T) new ViewModelProvider(fragment).get(modelClass);
    }

    @Override
    protected void onResume() {
        super.onResume();
        onResumeLoadData();
    }
}
